<template>
  <div class="resume-page-container">
    <div class="resume-content">
      <!-- 左侧上传区域 -->
      <a-card class="upload-section" title="简历上传">
        <a-form layout="vertical">
          <!-- 面试公司选择 -->
          <a-form-item label="面试公司">
            <a-select
              v-model:value="interviewInfo.companyId"
              :options="companyList"
              placeholder="请选择公司"
              style="width: 100%"
              allow-clear
              @change="handleCompanyChange"
            ></a-select>
          </a-form-item>

          <!-- 面试岗位选择 -->
          <a-form-item label="面试领域">
            <a-select
              v-model:value="interviewInfo.techFieldId"
              placeholder="请选择或输入岗位"
              :options="techFieldList"
              style="width: 100%"
              @change="handleTechFieldChange"
            ></a-select>
          </a-form-item>
          <a-form-item label="面试岗位">
            <a-select
              v-model:value="interviewInfo.positionId"
              placeholder="请选择或输入笔试的岗位"
              :options="positionList"
              style="width: 100%"
            ></a-select>
          </a-form-item>
        </a-form>
        <div class="upload-area">
          <a-upload-dragger
            :custom-request="handleUpload"
            :before-upload="beforeUpload"
            accept=".pdf,.doc,.docx"
            :show-upload-list="false"
            style="height: 100%; width: 100%"
          >
            <p class="ant-upload-drag-icon">
              <upload-outlined />
            </p>
            <p class="upload-text">点击或将文件拖拽到这里上传</p>
            <p class="upload-hint">支持 PDF、Word 格式</p>
          </a-upload-dragger>
        </div>
      </a-card>

      <!-- 右侧历史记录 -->
      <a-card class="history-section" title="历史简历">
        <div class="search-bar">
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索简历"
            style="width: 100%"
            @search="fetchResumeList"
          />
        </div>

        <a-table
          :columns="columns"
          :data-source="resumeList"
          :pagination="{ pageSize: 10 }"
          :loading="loading"
        >
          <!-- 自定义表格列 -->
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'resumeStatus'">
              <a-tag :color="getStatusColor(record.resumeStatus)"
                >{{ getStatusName(record.resumeStatus) }}
              </a-tag>
            </template>
            <template v-if="column.key === 'createTime'">
              {{ formatDate(record.createTime) }}
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button type="link" style="color: #999999" @click="showResume(record.resumeUrl)"
                  >预览
                </a-button>
                <a-button type="link" v-if="record.resumeStatus === 2" @click="viewAnalysis(record)"
                  >查看分析
                </a-button>
                <a-button type="link" danger @click="() => handleDelete(record.id)">删除</a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </div>
  <!-- PDF预览 -->
  <a-modal v-model:visible="previewVisible" width="45%" height="50%" :footer="null">
    <div class="pdf-container">
      <vue-pdf-embed
        v-for="page in 3"
        :key="page"
        :source="pdfUrl"
        :page="page"
        style="border: 1px solid #e8e8e8; margin-bottom: 16px"
      />
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import {
  deleteResumeUsingGet,
  searchResumeUsingGet,
  uploadFileUsingPost,
} from '@/api/resumeController'
import VuePdfEmbed from 'vue-pdf-embed'
import dayjs from 'dayjs'
import {
  getCompanyListUsingGet, getPositionListUsingGet,
  getTechFieldAndPositionUsingGet,
  getTechFieldListUsingGet
} from '@/api/positionController'

interface ResumeRecord {
  id: string
  resumeName: string
  resumeUrl: string
  resumeAnalyzeResultId: string
  resumeStatus: number
  createTime: string
}

const router = useRouter()
//搜索关键词
const searchKeyword = ref('')
const loading = ref(false)
//上传简历列表信息
const resumeList = ref<ResumeRecord[]>([])


//面试信息
const interviewInfo = ref({
  companyId: '',
  techFieldId: '',
  positionId: ''
})

// 公司列表
const companyList = ref([])

// 技术领域
const techFieldList = ref([])
// 面试岗位
const positionList = ref([])

// 表格列定义
const columns = [
  {
    title: '简历名称',
    dataIndex: 'resumeName',
    key: 'resumeName',
    width: '30%',
  },
  {
    title: '上传时间',
    dataIndex: 'createTime',
    key: 'createTime',
    sorter: (a: ResumeRecord, b: ResumeRecord) =>
      new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
  },
  {
    title: '状态',
    dataIndex: 'resumeStatus',
    key: 'resumeStatus',
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
  },
]

const previewVisible = ref(false)
const pdfUrl = ref('')

/**
 * 预览简历
 */
const showResume = (resumeUrl: string) => {
  previewVisible.value = true
  pdfUrl.value = resumeUrl
  console.log(pdfUrl)
}

/**
 * 删除简历
 */
const handleDelete = async (resumeId: string) => {
  const data = await deleteResumeUsingGet({
    resumeId: resumeId as any,
  })
  if (data.code === 0) {
    if (data.data) {
      message.success('删除成功')
      await fetchResumeList()
    } else {
      message.error('删除失败')
    }
  }
}

// 上传前检查文件类型和大小
const beforeUpload = (file: File) => {
  if(!interviewInfo.value.companyId || !interviewInfo.value.techFieldId || !interviewInfo.value.positionId){
    message.error('请填写完整信息')
    return false
  }
  const isPDF = file.type === 'application/pdf'
  const isWord =
    file.type === 'application/msword' ||
    file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

  if (!isPDF && !isWord) {
    message.error('只支持上传PDF或Word文件!')
    return false
  }

  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('文件必须小于5MB!')
    return false
  }

  return isPDF || isWord
}
/**
 * 文件上传
 * @param file 简历文件
 */
const handleUpload = async ({ file }: any) => {
  message.success("请稍后查看简历分析结果")

  const params = {companyId: interviewInfo.value.companyId, techFieldId: interviewInfo.value.techFieldId, positionId: interviewInfo.value.positionId}
  const data = await uploadFileUsingPost(params,{}, file)
  if (data.code === 0) {
    await fetchResumeList()
    //清空旧数据
    interviewInfo.value = {
      companyId: '',
      techFieldId: '',
      positionId: ''
    }
  } else {
    message.error(data.message)
  }
}

// 根据状态获取标签颜色
const getStatusColor = (status: number) => {
  const colorMap: Record<number, string> = {
    2: 'success',
    1: 'processing',
    0: 'default',
  }
  return colorMap[status] || 'default'
}
//根据枚举获取对应的状态名称
const getStatusName = (status: number) => {
  const statusMap: Record<number, string> = {
    2: '已完成',
    1: '分析中',
    0: '未分析',
  }
  return statusMap[status] || '未知'
}

// 查看简历分析
const viewAnalysis = (record: ResumeRecord) => {
  router.push({
    path: `/api/analyze/resume`,
    query: {
      name: record.resumeName,
      id: record.id
    },
  })
}
/**
 * 获取用户简历请求
 */
const fetchResumeList = async () => {
  loading.value = true
  const data = await searchResumeUsingGet({ resumeName: searchKeyword.value })
  resumeList.value = data?.data as ResumeRecord[]
  loading.value = false
}
/**
 * 格式化时间
 */
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

/**
 * 修改面试领域后的回调函数
 */
const handleTechFieldChange = async () => {
  positionList.value = []
  interviewInfo.value.positionId = ''
  // 获取岗位信息
  await fetchPositionList()
}

/**
 * 修改公司后的回调函数
 */
const handleCompanyChange = async () => {
  techFieldList.value = []
  positionList.value = []
  interviewInfo.value.techFieldId = ''
  interviewInfo.value.positionId = ''
  //获取技术领域列表
  await fetchTechFieldList()
}

/**
 * 获取公司列表
 */
const fetchCompanyList = async () => {
  const data = await getCompanyListUsingGet()
  data.data.map((item) => {
    companyList.value.push({ value: item.id, label: item.name })
  })
}

/**
 * 获取技术领域列表
 */
const fetchTechFieldList = async () => {
  const data = await getTechFieldListUsingGet()
  data.data.map((item) => {
    techFieldList.value.push({ value: item.id, label: item.name })
  })
}

/**
 * 根据公司id和技术领域id获取岗位列表
 */
const fetchPositionList = async () => {
  if(!interviewInfo.value.techFieldId || !interviewInfo.value.companyId) return
  const data = await getPositionListUsingGet({
    techFieldId: interviewInfo.value.techFieldId as any,
    companyId: interviewInfo.value.companyId as any,
  })
  data.data.map((item) => {
    positionList.value.push({ value: item.id, label: item.name })
  })
}

onMounted(() => {
  fetchResumeList()
  fetchCompanyList()
  fetchTechFieldList()
  fetchPositionList()
})
</script>

<style scoped>
.resume-page-container {
  height: 100%;
  padding: 24px;
  background-color: transparent;
}

.resume-content {
  display: flex;
  gap: 24px;
  height: 100%;
}

.upload-section {
  width: 30%;
  max-height: 100%;
}

.history-section {
  width: 70%;
  height: 100%;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  padding: 20px;
}

.upload-text {
  font-size: 16px;
  margin: 8px 0;
}

.upload-hint {
  color: #999;
}

.search-bar {
  margin-bottom: 16px;
}

:deep(.ant-upload-drag) {
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

:deep(.ant-card-head-title) {
  font-size: 18px;
  font-weight: 600;
}
</style>
